package com.imay.live.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.imay.base.fragment.BaseFragment;
import com.imay.live.activity.ProfileActivity;
import com.imay.live.activity.RoomLiveShortActivity;
import com.imay.live.activity.discovery.DynamicActivity;
import com.imay.live.activity.discovery.FollowControl;
import com.imay.live.adapter.NoticeListAdapter;
import com.imay.live.adapter.NoticeListFollowAdapter;
import com.imay.live.adapter.NoticeMergeListFollowAdapter;
import com.imay.live.adapter.NoticeMergeListMineAdapter;
import com.imay.live.analytics.MobclickAgent;
import com.imay.live.helper.EventHelper;
import com.imay.live.manager.AccountManager;
import com.imay.live.manager.DataSetListener;
import com.imay.live.manager.DataSetManager;
import com.imay.live.manager.UnreadManager;
import com.imay.live.model.NoticeMergeMineFollowModel;
import com.imay.live.model.NoticeMergeMineModel;
import com.imay.live.model.NoticeMineFollowModel;
import com.imay.live.model.NoticeModel;
import com.imay.live.proto.Result;
import com.imay.live.proto.helper.ProtoCallBack;
import com.imay.live.proto.helper.ProtoHttpFactory;
import com.imay.live.proto.helper.ProtoRequestHelper;
import com.imay.live.utils.RecyclerViewUtil;
import com.imay.live.view.refresh.RefreshView;
import com.imay.live.R;
import com.imay.tbas_api.IMYTBASObject;
import com.lcodecore.tkrefreshlayout.footer.LoadingView;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;

import java.util.ArrayList;
import java.util.List;

import static com.imay.live.manager.MessageManager.NewWarnType.IMBubbleCommentType;
import static com.imay.live.proto.ResultCode.CodeSuccess;

/**
 * create by nick
 * 通知fragment 里面的嵌套fragment
 */
public class NoticeChildFragment extends BaseFragment implements ProtoCallBack, BaseQuickAdapter.OnItemChildClickListener, DataSetListener {
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    public static final int TYPE_MINE = 1;
    public static final int TYPE_FOLLOW = 2;
    public static final int TYPE_MERGE_MINE = 3;
    public static final int TYPE_MERGE_FOLLOW = 4;

    private int tabType;
    private RecyclerView mNoticeListRV;
    private int maxId;
    private int count = 40;
    private int sinceId;
    private String loadMineNoticeConmand, loadFollowNoticeCommand, loadMineMergeNoticeCommand, loadMineFollowNoticeCommand;
    private List<NoticeModel> mineModels;
    private List<NoticeMineFollowModel> followModels;
    private List<NoticeMergeMineModel> noticeMergeMineModels;
    private List<NoticeMergeMineFollowModel> noticeMergeMineFollowModels;
    private NoticeListAdapter mineAdapter;
    private NoticeListFollowAdapter followModelAdapter;
    private NoticeMergeListMineAdapter noticeMergeListMineAdapter;
    private NoticeMergeListFollowAdapter noticeMergeListFollowAdapter;
    private long messageId;
    private TwinklingRefreshLayout notice_trl_refresh;
    private IMYTBASObject followChangeListener;
    private FollowControl followControl;

    private boolean isInstance = true;
    private DataSetManager mDataSetManager;

    public static NoticeChildFragment newInstance(int type, long messageId) {
        NoticeChildFragment fragment = new NoticeChildFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_PARAM1, type);
        args.putLong(ARG_PARAM2, messageId);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_notice_child;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        if (getArguments() != null) {
            tabType = getArguments().getInt(ARG_PARAM1);
            messageId = getArguments().getLong(ARG_PARAM2);
        }
        bindViews();
        initData();
        loadData();
        addListener();
        registerSocketNotify();
        mDataSetManager = DataSetManager.Builder.create(this).build();

    }

    private void addListener() {
        notice_trl_refresh.setOnRefreshListener(new RefreshListenerAdapter() {
            @Override
            public void onRefresh(final TwinklingRefreshLayout refreshLayout) {
                refreshData();
            }

            @Override
            public void onLoadMore(TwinklingRefreshLayout refreshLayout) {
                loadMore();
            }
        });
    }

    private void bindViews() {
        mNoticeListRV = $(R.id.rv_notice_list);
        notice_trl_refresh = $(R.id.notice_trl_refresh);
        RecyclerViewUtil.setLinearLayoutManagerWithoutDivider(getActivity(), mNoticeListRV);
        if (tabType == TYPE_MINE || tabType == TYPE_FOLLOW) {
            RefreshView headerView = new RefreshView(getActivity());
            notice_trl_refresh.setHeaderView(headerView);
            notice_trl_refresh.setBottomView(new LoadingView(getActivity()));
            notice_trl_refresh.setEnableLoadmore(true);
            notice_trl_refresh.setEnableOverScroll(false);
        } else {
            notice_trl_refresh.setEnableLoadmore(false);
            notice_trl_refresh.setEnableRefresh(false);
            notice_trl_refresh.setPadding(0, 0, 0, 0);
            notice_trl_refresh.setEnableOverScroll(false);
        }
    }

    private void initData() {
        switch (tabType) {
            case TYPE_MINE:
                mineModels = new ArrayList<>();
                break;
            case TYPE_FOLLOW:
                followModels = new ArrayList<>();
                break;
            case TYPE_MERGE_MINE:
                noticeMergeMineModels = new ArrayList<>();
                break;
            case TYPE_MERGE_FOLLOW:
                noticeMergeMineFollowModels = new ArrayList<>();
                break;
        }
    }


    @Override
    public void loadData() {
        if (isCreate) {
            if (AccountManager.getInstance().isLogined()) {
                if (isInstance) {
                    isInstance = false;
                    refreshDatas();
                }
            }
        }
    }

    private void refreshDatas() {
        switch (tabType) {
            case TYPE_MINE:
                loadMineNoticeConmand = ProtoRequestHelper.task(ProtoHttpFactory.getNoticeMine(maxId, sinceId, count)).setTag(this.hashCode()).request(this);
                break;
            case TYPE_FOLLOW:
                loadFollowNoticeCommand = ProtoRequestHelper.task(ProtoHttpFactory.getNoticeMineFollow(maxId, sinceId, count)).setTag(this.hashCode()).request(this);
                break;
            case TYPE_MERGE_MINE:
                loadMineMergeNoticeCommand = ProtoRequestHelper.task(ProtoHttpFactory.getMineNoticeMerge(messageId)).setTag(this.hashCode()).request(this);
                break;
            case TYPE_MERGE_FOLLOW:
                loadMineFollowNoticeCommand = ProtoRequestHelper.task(ProtoHttpFactory.getMineFollowNoticeMerge(messageId)).setTag(this.hashCode()).request(this);
                break;
        }
    }

    @Override
    public void clearData() {
        isInstance = true;
        switch (tabType) {
            case TYPE_MINE:
                if (mineModels != null) {
                    mineModels.clear();
                    UnreadManager.getInstance().postUnreadEvent(IMBubbleCommentType, 0);
                    bindAdapter();
                }
                break;
            case TYPE_FOLLOW:
                if (followModels != null) {
                    followModels.clear();
                    bindFollowAdapter();
                }
                break;
            case TYPE_MERGE_MINE:
                if (noticeMergeMineModels != null) {
                    noticeMergeMineModels.clear();
                    bindNoticeMergeMineAdapter();
                }
                break;
            case TYPE_MERGE_FOLLOW:
                loadMineFollowNoticeCommand = ProtoRequestHelper.task(ProtoHttpFactory.getMineFollowNoticeMerge(messageId)).setTag(this.hashCode()).request(this);
                if (noticeMergeMineFollowModels != null) {
                    noticeMergeMineFollowModels.clear();
                    bindNoticeMergeFollowAdapter();
                }
                break;
        }
    }


    @Override
    public void onRequestSuccess(String command, String data) {
        refreshFinish();
        if (command.equals(loadMineNoticeConmand)) {
            Result<List<NoticeModel>> result = JSON.parseObject(data, new TypeReference<Result<List<NoticeModel>>>() {
            }.getType());
            if (result.result == CodeSuccess) {
                if (maxId == 0) {
                    mineModels.clear();
                    UnreadManager.getInstance().postUnreadEvent(IMBubbleCommentType, 0);
                }
                mineModels.addAll(result.data);
                bindAdapter();
            }
        } else if (command.equals(loadFollowNoticeCommand)) {
            Result<List<NoticeMineFollowModel>> result = JSON.parseObject(data, new TypeReference<Result<List<NoticeMineFollowModel>>>() {
            }.getType());
            if (result.result == CodeSuccess) {
                if (maxId == 0) {
                    followModels.clear();
                }
                followModels.addAll(result.data);
                bindFollowAdapter();
            }
        } else if (command.equals(loadMineMergeNoticeCommand)) {
            Result<List<NoticeMergeMineFollowModel>> result = JSON.parseObject(data, new TypeReference<Result<List<NoticeMergeMineFollowModel>>>() {
            }.getType());
            if (result.result == CodeSuccess) {
                noticeMergeMineModels.addAll(result.data);
                bindNoticeMergeMineAdapter();
            }
        } else if (command.equals(loadMineFollowNoticeCommand)) {
            Result<List<NoticeMergeMineFollowModel>> result = JSON.parseObject(data, new TypeReference<Result<List<NoticeMergeMineFollowModel>>>() {
            }.getType());
            if (result.result == CodeSuccess) {
                noticeMergeMineFollowModels.addAll(result.data);
                bindNoticeMergeFollowAdapter();
            }
        }


    }

    @Override
    public void onRequestError(String command, int code, String message) {
        refreshFinish();

    }

    private void bindAdapter() {
        if (mineAdapter == null) {
            mineAdapter = new NoticeListAdapter(R.layout.item_notice_mine, mineModels);
            mNoticeListRV.setAdapter(mineAdapter);
            mineAdapter.setOnItemChildClickListener(this);
            mineAdapter.setEmptyView(LayoutInflater.from(getActivity()).inflate(R.layout.view_load_layout, null));
        } else {
            mineAdapter.setNewData(mineModels);
            mineAdapter.notifyDataSetChanged();
        }
        notice_trl_refresh.setEnableLoadmore(!mineModels.isEmpty());


    }

    private void bindFollowAdapter() {
        if (followModelAdapter == null) {
            followModelAdapter = new NoticeListFollowAdapter(R.layout.item_notice_mine, followModels);
            mNoticeListRV.setAdapter(followModelAdapter);
            followModelAdapter.setOnItemChildClickListener(this);
            followModelAdapter.setEmptyView(LayoutInflater.from(getActivity()).inflate(R.layout.view_load_layout, null));
        } else {
            followModelAdapter.setNewData(followModels);
            followModelAdapter.notifyDataSetChanged();

        }
        notice_trl_refresh.setEnableLoadmore(!followModels.isEmpty());

    }

    private void bindNoticeMergeMineAdapter() {
        if (noticeMergeListMineAdapter == null) {
            noticeMergeListMineAdapter = new NoticeMergeListMineAdapter(R.layout.item_notice_mine, noticeMergeMineModels);
            mNoticeListRV.setAdapter(noticeMergeListMineAdapter);
            noticeMergeListMineAdapter.setOnItemChildClickListener(this);
        } else {
            noticeMergeListMineAdapter.setNewData(noticeMergeMineModels);
            noticeMergeListMineAdapter.notifyDataSetChanged();

        }

    }

    private void bindNoticeMergeFollowAdapter() {
        if (noticeMergeListFollowAdapter == null) {
            noticeMergeListFollowAdapter = new NoticeMergeListFollowAdapter(R.layout.item_notice_mine, noticeMergeMineFollowModels);
            mNoticeListRV.setAdapter(noticeMergeListFollowAdapter);
            noticeMergeListFollowAdapter.setOnItemChildClickListener(this);
        } else {
            noticeMergeListFollowAdapter.setNewData(noticeMergeMineFollowModels);
            noticeMergeListFollowAdapter.notifyDataSetChanged();

        }
    }


    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
        Object obj = adapter.getData().get(position);
        if (tabType == NoticeChildFragment.TYPE_FOLLOW) {
            MobclickAgent.onEvent(getActivity(), "news_click_content");
        }
        switch (view.getId()) {
            case R.id.iv_notice_head_img:
                if (obj instanceof NoticeMineFollowModel) {
                    NoticeMineFollowModel model = (NoticeMineFollowModel) obj;
                    long uid = model.getOperatorUser().get(0).getUid();
                    ProfileActivity.start(getActivity(), uid);
                } else if (obj instanceof NoticeModel) {
                    NoticeModel model = (NoticeModel) obj;
                    long uid = model.getUsers().get(0).getUid();
                    ProfileActivity.start(getActivity(), uid);
                } else if (obj instanceof NoticeMergeMineFollowModel) {
                    NoticeMergeMineFollowModel model = (NoticeMergeMineFollowModel) obj;
                    long uid = model.getOperatorUser().getUid();
                    ProfileActivity.start(getActivity(), uid);
                } else if (obj instanceof NoticeMergeMineModel) {
                    NoticeMergeMineModel model = (NoticeMergeMineModel) obj;
                    long uid = model.getUser().getUid();
                    ProfileActivity.start(getActivity(), uid);
                }
                break;
            case R.id.iv_notice_right:
                if (obj instanceof NoticeMineFollowModel) {
                    NoticeMineFollowModel model = (NoticeMineFollowModel) obj;
                    if (model.getEventType() == 9) {
                        long shortLiveId = model.getShortLive().getShortLiveId();
                        RoomLiveShortActivity.startLiveActivity(getActivity(), shortLiveId, true);
                    } else {
                        long feedId = model.getFeeds().get(0).getId();
                        DynamicActivity.start(getActivity(), feedId, getString(R.string.str_imay_photo));
                    }
                } else if (obj instanceof NoticeModel) {
                    NoticeModel model = (NoticeModel) obj;
                    if (model.getEventType() == 9) {
                        long shortLiveId = model.getShortLive().getShortLiveId();
                        RoomLiveShortActivity.startLiveActivity(getActivity(), shortLiveId, true);
                    } else {
                        long feedId = model.getFeeds().get(0).getId();
                        DynamicActivity.start(getActivity(), feedId, getString(R.string.str_imay_photo));
                    }
                } else if (obj instanceof NoticeMergeMineFollowModel) {
                    NoticeMergeMineFollowModel model = (NoticeMergeMineFollowModel) obj;
                    if (model.getEventType() != 9) {
                        long feedId = model.getFeed().getId();
                        DynamicActivity.start(getActivity(), feedId, getString(R.string.str_imay_photo));
                    }
                } else if (obj instanceof NoticeMergeMineModel) {
                    NoticeMergeMineModel model = (NoticeMergeMineModel) obj;
                    if (model.getEventType() != 9) {
                        long feedId = model.getFeed().getId();
                        DynamicActivity.start(getActivity(), feedId, getString(R.string.str_imay_photo));
                    }
                }
                break;
            case R.id.cb_notice_follow:
                if (followControl == null) {
                    followControl = new FollowControl();
                }
                if (obj instanceof NoticeModel) {
                    NoticeModel model = (NoticeModel) obj;
                    followControl.followChanged(getActivity().getApplicationContext(), model.getUsers().get(0), false);
                }
                if (obj instanceof NoticeMergeMineModel) {
                    NoticeMergeMineModel model = (NoticeMergeMineModel) obj;
                    followControl.followChanged(getActivity().getApplicationContext(), model.getUser(), false);
                }

                break;

        }
    }

    public void refreshData() {
        sinceId = 0;
        maxId = 0;
        refreshDatas();
    }

    public void loadMore() {
        switch (tabType) {
            case TYPE_MINE:
                if (mineModels.size() > 0) {
                    maxId = mineModels.get(mineModels.size() - 1).getId();
                }
                break;
            case TYPE_FOLLOW:
                if (followModels.size() > 0) {
                    maxId = followModels.get(followModels.size() - 1).getId();
                }
                break;
        }
        refreshDatas();
    }

    private void refreshFinish() {
        if (notice_trl_refresh != null) {
            if (maxId == 0) {
                notice_trl_refresh.finishRefreshing();
            } else {
                notice_trl_refresh.finishLoadmore();
            }
        }
    }

    protected void registerSocketNotify() {
        followChangeListener = new IMYTBASObject(false);
        followChangeListener.stringCommand = EventHelper.EVENT_FOLLOW_UICHANGE;
        followChangeListener.setDataResultListener(new IMYTBASObject.OnDataResultListener() {
            @Override
            public void onCommandTaskSuccess(final IMYTBASObject object) {
                refreshFollowStatus(object.stringData);
            }
        });
        followChangeListener.addEventListenWithTBASObject();

    }

    private void refreshFollowStatus(String uidStr) {
        boolean isFollow = true;
        int sp = uidStr.indexOf("#");
        if (sp > 0) {
            uidStr = uidStr.substring(0, sp);
            isFollow = false;
        }
        int uid = Integer.parseInt(uidStr);
        int position = -1;
        if (mineModels != null) {
            for (int i = 0; i < mineModels.size(); i++) {
                NoticeModel model = mineModels.get(i);
                if (model.getEventType() == 1 && !model.isMerge()) {
                    if (mineModels.get(i).getUsers().get(0).getUid() == uid) {
                        position = i;
                        mineModels.get(i).getUsers().get(0).setMyFollow(isFollow);
                        break;
                    }
                }
            }
            final int finalPosition = position;
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (finalPosition != -1) {
                        mineAdapter.notifyItemChanged(finalPosition);
                    }
                }
            });
        }
        if (noticeMergeMineModels != null) {
            for (int i = 0; i < noticeMergeMineModels.size(); i++) {
                NoticeMergeMineModel model = noticeMergeMineModels.get(i);
                if (model.getEventType() == 1) {
                    if (noticeMergeMineModels.get(i).getUser().getUid() == uid) {
                        position = i;
                        noticeMergeMineModels.get(i).getUser().setMyFollow(isFollow);
                        break;
                    }
                }
            }
            final int finalPosition = position;
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (finalPosition != -1) {
                        noticeMergeListMineAdapter.notifyItemChanged(finalPosition);
                    }
                }
            });
        }
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        if (followChangeListener != null) {
            followChangeListener.destroy();
        }
        if (mDataSetManager != null) {
            mDataSetManager.unregisterDataNotify();
        }
    }

    boolean isCreated;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        isCreated = true;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        // 友盟统计页面跳转，重写此方法，可以保证ViewPager切换Fragment时能够准确的记录Fragment之间的跳转
        // 不用再调用Fragment的生命周期方法
        if (isCreated) {
            if (isVisibleToUser) {
                MobclickAgent.onPageStart(getClass().getSimpleName());
            } else {
                MobclickAgent.onPageEnd(getClass().getSimpleName());
            }
        }
    }

}
